"""启动文件"""

import cv2
import numpy as np
import pyautogui
import subprocess
import time
import os
from PIL import ImageGrab

from src.daily_tasks import daily_tasks
from src.utils import click_screen_position

# 游戏启动配置
exe_path = r"E:\game\AetherGazerStarter\AetherGazerStarter.exe"
game_dir = r"E:\game\AetherGazerStarter"
template_path = os.path.join('templates', 'start_button.png')
target_interface_template = os.path.join('templates', 'before_play.png')  # 目标界面模板图路径


def find_button_position(template_path, threshold=0.8):
    """使用模板匹配找到按钮位置"""
    screenshot = ImageGrab.grab()
    screenshot = np.array(screenshot)
    screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)

    template = cv2.imread(template_path)
    if template is None:
        raise FileNotFoundError(f"无法加载模板图片: {template_path}")

    result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    if max_val >= threshold:
        h, w = template.shape[:2]
        return (max_loc[0] + w // 2, max_loc[1] + h // 2)
    return None


def wait_for_interface(target_template, timeout=30, check_interval=2):
    """等待目标界面出现（模板匹配检测）"""
    start_time = time.time()
    while time.time() - start_time < timeout:
        # 获取当前屏幕截图
        screenshot = ImageGrab.grab()
        screenshot = np.array(screenshot)
        screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)

        # 加载目标界面模板
        target = cv2.imread(target_template)
        if target is None:
            raise FileNotFoundError(f"无法加载目标界面模板: {target_template}")

        # 执行模板匹配
        result = cv2.matchTemplate(screenshot, target, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, _, _ = cv2.minMaxLoc(result)

        if max_val >= 0.7:  # 设定匹配阈值
            print("检测到目标界面加载完成！")
            return True

        time.sleep(check_interval)
    return False



def click_button(button_position, show_click=True):
    """模拟鼠标点击按钮，并可视化点击位置"""
    if button_position:
        x, y = button_position

        if show_click:
            screenshot = np.array(ImageGrab.grab())
            screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
            cv2.circle(screenshot, (x, y), 20, (0, 0, 255), 2)
            cv2.putText(screenshot, f"Click: ({x}, {y})", (x + 30, y),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
            cv2.imshow("Click Position", screenshot)
            cv2.waitKey(3000)
            cv2.destroyAllWindows()

        pyautogui.moveTo(x, y, duration=0.5)
        pyautogui.click()
        return True
    return False


def start_game():
    """启动游戏启动器并返回进程对象"""
    try:
        process = subprocess.Popen(exe_path, cwd=game_dir)
        print("游戏启动器启动成功！")
        return process
    except Exception as e:
        print(f"启动游戏失败: {e}")
        return None


def main():
    # 1. 启动游戏启动器
    game_process = start_game()

    if not game_process:
        print("启动器启动失败，请检查路径配置")
        return

        # 2. 动态检测启动器界面加载完成（优化点）
    print("等待启动器加载...")
    # 使用开始按钮作为启动器界面加载完成的标志
    if not wait_for_interface(template_path, timeout=30, check_interval=2):  # 检测间隔缩短到2秒
        print("启动器界面加载超时")
        return

    # 3. 循环检测开始按钮（优化后只需检测1次）
    print("立即检测开始按钮...")
    button_pos = find_button_position(template_path)

    if click_button(button_pos):
        print("游戏主程序启动中...")
        # 4. 优化游戏主体加载等待（动态检测）
        print("等待目标界面加载...")
        if wait_for_interface(target_interface_template, timeout=60, check_interval=1):
            print("检测到目标界面，等待3秒后点击...")
            time.sleep(3)
            click_screen_position(clicks=2)
            time.sleep(2)
            click_screen_position(clicks=1)
            return
        else:
            print("错误：超时未检测到目标界面")
            return
    else:
        print("错误：未找到开始按钮，请手动检查")


if __name__ == "__main__":
    pyautogui.FAILSAFE = True
    pyautogui.PAUSE = 1.0
    main()
    daily_tasks()
